package com.itasura.guava.Concurrency.mointor;

import com.itasura.guava.bean.City;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * condition 版
 * 依然需要使用while循环，但是有一个好处，我们可以定义两个Condition，这样我们就可以用signal来替代signalAll，这样可能会带来一点性能上的提升
 *
 * @author sailor wang
 * @date 2018/10/30 11:17 AM
 * @description
 */
@Slf4j
public class SafeBoxV2<V> {

    private final ReentrantLock lock = new ReentrantLock();

    private final Condition valuePresent = lock.newCondition();

    private final Condition valueAbsent = lock.newCondition();

    private V value;

    public V get() throws InterruptedException {
        lock.lock();
        try {
            while (value == null) {
                valuePresent.await();
            }
            V result = value;
            value = null;
            valueAbsent.signal();
            return result;
        } finally {
            lock.unlock();
        }
    }

    public void set(V newValue) throws InterruptedException {
        try {
            lock.lock();
            if (value != null) {
                valueAbsent.await();
            }
            value = newValue;
            valuePresent.signal();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {


        SafeBoxV2<City> safeBox = new SafeBoxV2<City>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    log.info("开始获取值......");
                    City c = safeBox.get();
                    log.info("获取完成，值 -> {}", c);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Thread.sleep(2000);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    City city = new City();
                    city.setName("上海");
                    log.info("开始设置值......");
                    safeBox.set(city);
                    log.info("设置完成......");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}